package zheezes.swt.databinding;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Collection;

import org.eclipse.jface.databinding.viewers.TreeStructureAdvisor;

public final class TreeBeanAdvisor extends TreeStructureAdvisor {
	private final Class<?> clazz;
	private final Method getParentMethod;
	private final Method getChildrenMethod;
	private final Method hasChildrenMethod;
	
	public TreeBeanAdvisor(Class<?> clazz,
			String parentProperty,
			String childrenProperty,
			String hasChildrenProperty) {
		this.clazz = clazz;
		getParentMethod = CalssUtil.getMethod(this.clazz, parentProperty);
		getChildrenMethod = CalssUtil.getMethod(this.clazz, childrenProperty);
		hasChildrenMethod = CalssUtil.getMethod(this.clazz, hasChildrenProperty);
	}
	
	@Override
	public Object getParent(Object element) {
		return CalssUtil.invokeMethod(getParentMethod, clazz, element);
	}
	
	@Override
	public Boolean hasChildren(Object element) {
		if (hasChildrenMethod != null) {
			return (Boolean) CalssUtil.invokeMethod(hasChildrenMethod, clazz, element);
		}
		if (getChildrenMethod != null) {
			Object children = CalssUtil.invokeMethod(getChildrenMethod, clazz, element);
			if (children == null) {
				return Boolean.FALSE;
			}
			if (children.getClass().isArray()) {
				return Array.getLength(children) > 0;
			}
			if (children instanceof Collection<?>) {
				Collection<?> collection = (Collection<?>) children;
				return !collection.isEmpty();
			}
		}
		// return null;
		return false;
	}
}